package symbol;

public class OrderSymbolTable<Key extends Comparable<Key>, Value> {


    //记录首结点
    private Node head;
    //记录符号表中元素的个数
    private int N;

    public OrderSymbolTable() {
        head = new Node(null, null, null);
        N = 0;
    }

    //获取符号表中键值对的个数
    public int size() {
        return N;
    }

    //往符号表中插入键值对
    public void put(Key key, Value value) {
        Node current = head.next;
        Node pre = head;
        while (current != null && key.compareTo(current.key) > 0) {
            current = current.next;
            pre = pre.next;
        }
        if (current != null && current.key.compareTo(key) == 0) {
            current.value = value;
            return;
        }
        pre.next = new Node(key, value, current);

    }

    public void delete(Key key) {
        Node n = head;
        while (n.next != null) {
            if (n.next.key.equals(key)) {
                n.next = n.next.next;
                N--;
                return;
            }
            n = n.next;
        }
    }

    public Value get(Key key) {
        Node n = head;
        while (n.next != null) {
            Node current = n.next;
            if (current.key.equals(key)) {
                return current.value;
            }
            n = n.next;
        }
        return null;
    }


    private class Node {
        //键
        public Key key;
        //值
        public Value value;
        //下一个结点
        public Node next;

        public Node(Key key, Value value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        OrderSymbolTable<Integer, String> bt = new OrderSymbolTable<>();
        bt.put(4, "二哈");
        bt.put(3, "张三");
        bt.put(1, "李四");
        bt.put(1, "aa");
        bt.put(5, "王五");

    }
}
